package org.leo.study.common.interceptor;

import org.leo.study.common.config.SpringContext;
import org.leo.study.common.service.IdService;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 日志追踪拦截器
 * </p>
 *
 * @Package: org.leo.study.interceptor
 * @ClassName: LogTraceInterceptor
 * @author: Li.Junlin
 * @date: 2019.10.12 10:10
 */
public class LogTraceInterceptor implements HandlerInterceptor {
    /**
     * 追踪ID
     */
    private final static String TRACE_ID = "traceId";

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // 删除traceId
        MDC.remove(TRACE_ID);
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        IdService idService = SpringContext.getBean(IdService.class);
        // 设置 traceId
        String traceId = request.getHeader(TRACE_ID);
        traceId = traceId == null ? String.valueOf(idService.snowflakeId()) : traceId;

        MDC.put(TRACE_ID, traceId);
        return true;
    }
}
